package com.cml.sqlversionupgradestarter.service;

import cn.hutool.db.Entity;
import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.sql.SqlExecutor;
import com.cml.sqlversionupgradestarter.context.SQLVersionUpgradeContext;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * 作者：陈茂林
 * 时间：2022/1/6
 * 描述：
 */
public class SqlVersionCTLManager {
    private  Date curVersionDate;
    private SQLVersionUpgradeContext sqlVersionUpgradeContext;
    public SqlVersionCTLManager( SQLVersionUpgradeContext sqlVersionUpgradeContext){
        this.sqlVersionUpgradeContext=sqlVersionUpgradeContext;
    }


    public Date getCurVersionDate() throws SQLException {
        if(curVersionDate== null){
            try {
                this.curVersionDate= getVersion();

            } catch (SQLException e) {
                this.createVersionTable();
            }
        }

        return this.curVersionDate;
    }

    private  void createVersionTable() throws SQLException {
        StringBuilder sql= new StringBuilder();
        sql.append("create table db_version_ctl(" +
                "`id` int NOT NULL AUTO_INCREMENT,\n" +
                "  `version_date` datetime NULL,\n" +
                "  PRIMARY KEY (`id`)" +
                ")");

        SqlExecutor.execute(sqlVersionUpgradeContext.getJdbcConnManager().getConnection(), sql.toString());
    }

    private  Date getVersion()throws SQLException {
        List<Entity> entityList =SqlExecutor.query(sqlVersionUpgradeContext.getJdbcConnManager().getConnection(), "select * from db_version_ctl", new EntityListHandler());
        if(entityList.size()>0){
            return (Date)entityList.get(0).get("version_date");
        }
        return null;
    }

    public void  setCurVersionDate(Date versionDate) throws SQLException {
        try {
            List<Entity> entityList =SqlExecutor.query(sqlVersionUpgradeContext.getJdbcConnManager().getConnection(), "select * from db_version_ctl", new EntityListHandler());
            if(entityList.size()>0){
                SqlExecutor.executeUpdate(sqlVersionUpgradeContext.getJdbcConnManager().getConnection().prepareStatement("UPDATE db_version_ctl set version_date = ? "),versionDate);
            }else{

                SqlExecutor.execute(sqlVersionUpgradeContext.getJdbcConnManager().getConnection(), "insert into  db_version_ctl(version_date) values(?) ", versionDate);
            }
            //相同线程是同一个
            sqlVersionUpgradeContext.getJdbcConnManager().closeConnection(sqlVersionUpgradeContext.getJdbcConnManager().getConnection());
        }catch (Exception e){
            e.printStackTrace();

        }
    }
}
